package Try.Proxy.MineProxy;


import java.io.*;

public class MyClassLoader extends ClassLoader {
    private String baseDir;

    public MyClassLoader(){
        baseDir = this.getClass().getResource("").getPath();
    }

    /**
     * 通过类名称加载类字节码文件到JVM中
     * @param name 类名
     * @return 类的Class独享
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String className = MyClassLoader.class.getPackage().getName() + "." + name;
        if(null==baseDir){
            throw new ClassNotFoundException();
        }

        File file = new File(baseDir, name + ".class");
        if(!file.exists()){
            throw new ClassNotFoundException();
        }

        try(FileInputStream fileInputStream = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream();){
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fileInputStream.read(buffer))!=0){
                out.write(buffer,0,len);
            }

            return defineClass(className, out.toByteArray(), 0, out.size());
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
            e.printStackTrace();
        }


        return super.findClass(name);
    }
}